import config from "@/config/app.js";
module.exports = {
	CHECK_LOGIN: function(_that, model = '') { //判断登陆
		let authcode = uni.getStorageSync("authcode");
		if (authcode != '') {
			return true;
		}
		let pages = getCurrentPages();
		let page = pages[pages.length - 1];
		if (typeof(page) == 'undefined') { //未读取到页面信息
			return true;
		}
		if (model == 'channel') {
			if (page.route.indexOf('channel') < 0) {
				return false;
			}
			if (_that.config.channelLoginWhiteList.indexOf(page.route) == -1) {
				this.noLoginModal(page, '未登陆或登陆超时，请重新登陆.');
			}
		} else {
			this.noLoginModal(page, '未登陆或登陆超时，请重新登陆.', true);
		}
		return true;
	},
	getAuthCode: function() { //获取登陆授权码
		return uni.getStorageSync("authcode");
	},
	setAuthCode: function($authcode) { //设置登陆授权码
		uni.setStorageSync("authcode", $authcode);
	},
	delAuthCode: function() { //清理登陆授权码
		uni.removeStorageSync("wx_openid");
		uni.removeStorageSync("authcode");
	},
	getWxOpenId: function() { //获取微信openid
		return uni.getStorageSync("wx_openid");
	},
	setWxOpenId: function($openId) { //设置微信openid
		uni.setStorageSync("wx_openid", $openId);
	},
    /**
     * nvue 的请求，用的是另外的方法，不再请求这个方法了。
     * 所以，这里的url,原来是引用的根目录下的配置文件，应该是引用config/app文件。
     */
	nvueRequest: function(url, data = {}, functions) {
		let header = {};
		header.Token = uni.getStorageSync("authcode");
		header.appsessionid = uni.getStorageSync("session_id");
		header.uiType = 'uniapp';
		header.source = uni.getStorageSync("source_platform");
		uni.request({
			url: config.baseUrl + url,
			data: data,
			header: header,
			success: functions,
		})
	},
	objectToQueryString: function(obj) {
		return Object.keys(obj).map(function(key) {
			return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(obj[key]));
		}).join('&');
	},
	goPage: function(page, type = false) { //跳转页面
		if (page == -1) {
			uni.navigateBack({
				delta: 1
			});
			return false;
		}
		if (typeof(page) == 'object') {
			let options = this.objectToQueryString(page[1]);
			page = page[0] + '?' + options;
		}
		let pages = getCurrentPages();

		if (pages.length >= 10 && type != -1) {
			uni.reLaunch({
				url: page
			});
			return false;
		}
		if (type === false) {
			uni.navigateTo({
				url: page,
				fail: (e) => {
					uni.switchTab({
						url: page
					});
				}
			});
			return false;
		}
		if (type == -1) {
			uni.redirectTo({
				url: page
			});
			return false;
		}
		uni.switchTab({
			url: page
		});
	},
	noLoginModal: function(page, msg, forcibly = false) { //未登陆统一提示操作
		if (uni.getStorageSync("isNotLoginTip") == 1 && forcibly == false) {
			return false;
		}
		// uni.setStorageSync("isNotLoginTip", 1);

		let platform = this.getPlatform();
		let returnUrl = '';
		if (typeof(page) == 'object') {
			returnUrl = encodeURIComponent(page.route + '?' + this.objectToQueryString(page.options));
		}

		if (page.route.indexOf('channel') >= 0 || page.route.indexOf('school') >= 0) {
			uni.showModal({
				title: '提示',
				content: msg,
				showCancel: false,
				success: function(res) {
					if (res.confirm) {
						uni.redirectTo({
							url: '/pagesB/channel/passport/login?returnUrl=' + returnUrl
						});
					}
				}
			});
		} else {
			let loginUrl = '';
			if (platform == 'MP-WEIXIN') {
				loginUrl = '/pages/member/passport/authorization?returnUrl=' + returnUrl;
			} else {
				loginUrl = '/pages/member/passport/login?returnUrl=' + returnUrl;
			}
			// loginUrl = '/pages/member/passport/login?returnUrl=' + returnUrl;
			if (forcibly == true) { //强制必须登陆
				uni.showModal({
					title: '提示',
					content: msg,
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							// uni.removeStorageSync("isNotLoginTip");
							uni.navigateTo({
								url: loginUrl
							});
						}
					}
				});
			} else { //不强制，一般api请求返回未登陆时调用
				uni.showModal({
					title: '提示',
					content: msg,
					showCancel: true,
					confirmText: '前往登录',
					cancelText: '暂不登录',
					success: function(res) {
						uni.removeStorageSync("isNotLoginTip");
						if (res.confirm) {
							uni.navigateTo({
								url: loginUrl
							});
						}
					}
				});
			}
		}
	},
	showModal: function(title, page = 0, type = false) { //提示并跳转
		let that = this;
		uni.showModal({
			title: '提示',
			content: title,
			showCancel: false,
			success: function(res) {
				if (res.confirm) {
					if (page == 0) {
						return true;
					}
					that.goPage(page, type);
				}
			}
		});
	},
	showToast(title, page = '', type = false, time = 1500, icon = 'none') { //弹窗并跳转
		let that = this
		uni.showToast({
			title: title,
			icon: icon,
			duration: time,
			mask: true,
		});
		if (type == false && page != '') {
			setTimeout(function() {
				if (page == 0) {
					return true;
				}
				if (page == -1) {
					uni.navigateBack();
				} else {
					that.goPage(page, type);
				}
				uni.hideToast();
			}, time)
		}
	},
	showImg(pic, _current = 0, baseUrl = '') { //点击查看图片
		if (typeof(pic) == 'string') {
			var pics = [];
			pics.push(pic);
		} else {
			var pics = [];
			if (baseUrl !== '') {
				pic.forEach((item, index) => {
					pics.push(baseUrl + item);
				})
			} else {
				pics = pic;
			}
		}
		// 预览图片
		uni.previewImage({
			current: _current,
			urls: pics,
		})
	},
	pxToRpx(px) { //px转rpx
		const info = uni.getSystemInfoSync();
		if (px <= 0) return 0;
		let scale = 750 / info.windowWidth;
		return px * scale;
	},
	toParams(options) { //转换参数
		let params = Object.keys(options).map(function(key) {
			return encodeURIComponent(key) + "=" + encodeURIComponent(options[key]);
		}).join("&");
		return params;
	},
	//设置C端主题色
	setCStyle(from) {
		if (from == 'channel') {
			return '';
		}
		return 'baseA';
	},
	//获取默认颜色
	getColor(_that) {
		return _that.config.defaultColor;
	},
	//判断来源平台，暂只判断H5,app,微信小程序
	getPlatform() {
		let platform = uni.getStorageSync("source_platform");
		if (platform == '') {
			platform = 'other'; //默认其它
			// #ifdef H5
			platform = 'H5';
			let ua = window.navigator.userAgent.toLowerCase()
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				platform = 'H5-WX';
			}
			// #endif
			// #ifdef APP-PLUS
			switch (uni.getSystemInfoSync().platform) {
				case 'android':
					platform = 'android';
					break;
				case 'ios':
					platform = 'ios';
					break;
			}
			platform = 'APP';
			// #endif
			// #ifdef MP-WEIXIN
			platform = 'MP-WEIXIN';
			// #endif
		}
		uni.setStorageSync("source_platform", platform);
		return platform;
	},
	//微信授权获取用户openid
	getWxOauthOpenId(_this, query) {

		let openId = this.getWxOpenId();
		if (openId != '') return true;
		let platform = this.getPlatform();
		if (platform != 'H5-WX' && platform != 'MP-WEIXIN') {
			return;
		}
		let share_token = uni.getStorageSync("share_token"); //获取邀请码
		if (platform == 'MP-WEIXIN') {
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					_this.$u.post(
							`weixin/api.index/getOpenId?type=MP&code=${loginRes.code}&share_token=${share_token}`
						)
						.then(res => {
							_this.app.setWxOpenId(res.data.openid);
						});
				},
				fail: function(err) {}
			});
		} else {
			let setting = uni.getStorageSync("setting");
			if (setting.weixin_is_used != 1) {
				return; //不使用公众号，不进行跳转
			}
			if (!query.code) {
				const href = encodeURI(window.location.href);
				window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?
														appid=${setting.weixin_appid}&
														redirect_uri=${href}&
														response_type=code&
														scope=snsapi_userinfo&
														state=STATE#wechat_redirect`;
				return;
			}

			_this.$u.post(`weixin/api.index/getOpenId?type=H5-WX&code=${query.code}&share_token=${share_token}`)
				.then(res => {
					_this.app.setWxOpenId(res.data.openid);
				});
		}
	},
	// APP图片上传处理
	async appReadFileToBase64(path, callback) {
		return new Promise((resolve, reject) => {
			plus.io.resolveLocalFileSystemURL(path, function(entry) {
				entry.file(function(file) {
					var AppReader = new plus.io.FileReader();
					AppReader.onloadend = function(e) {
						let base64 = e.target.result
						//resolve(base64.split(",")[1])  
						callback(base64);
					};
					AppReader.onerror = function(err) {
						reject(err)
					};
					AppReader.readAsDataURL(file);
				}, function(e) {
					reject(e)

				});
			});

		})

	},
	// 小程序图片上传处理
	wxmpReadFileToBase64(path, callback) {
		wx.getFileSystemManager().readFile({
			filePath: path, //选择图片返回的相对路径
			encoding: 'base64', //编码格式
			success: res => {
				//成功的回调
				let base64 = 'data:image/' + path.substring(path.indexOf('.') + 1).toLowerCase() +
					';base64,' + res.data; //拼接后返回
				callback(base64);
			}
		});
	},
	//复制
	copy(text) {
		uni.setClipboardData({
			data: text,
			success: function(data) {
				uni.showToast({
					title: '复制成功.',
					duration: 2000,
				});
			},
			fail: function(err) {
				uni.showToast({
					title: '复制失败，请重试.',
					icon: 'none',
					duration: 2000
				});
			},
			complete: function(res) {}
		})
	},
}